<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test WebSocket</title>
    <input type="text" id="message">
    <button id="send-button">发送</button>
</head>
<body>

    <script>
        //创建一个 webSocket 实例
        //ws表示协议名
        let webSocket = new WebSocket("ws://127.0.0.1:8080/test");

        //给这个 webSocket 注册上一些回调函数
        webSocket.onopen = function() {
            //建立完成之后，就自动执行这个回调函数
            console.log("webSocket 连接成功");
        }

        webSocket.onclose = function() {
            //连接断开后，执行
            console.log("webSocket 断开连接");
        }

        webSocket.onerror = function() {
            //连接异常时，执行
            console.log("webSocket 连接异常");
        }

        webSocket.onmessage = function(e) {
            //收到消息时，执行
            console.log("webSocket 收到消息" + e.data);
        }

        let messageInput = document.querySelector('#message');
        let sendbutton = document.querySelector("#send-button");
        sendbutton.onclick = function() {
            console.log("发送消息:" + messageInput.value);
            webSocket.send(messageInput.value);

        }
    </script>
    
</body>
</html>